package table

import (
	"errors"
	. "go_tempate/SQL/gormDB"
	"gorm.io/gorm"
)

// 密保问题查询表
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
type SecurityType struct {
	gorm.Model
	Name string `gorm:"type:varchar(32);not null;comment:'密保问题名称'"`
}

// 在sql创建之前
// ----------------------------------------------------------------------------------------------------------
func (s *SecurityType) BeforeCreate(tx *gorm.DB) (err error) {
	var count int64
	if err := tx.Model(&SecurityType{}).Where("name = ? ", s.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("密保问题不能重复,请勿重复创建")
	}
	return nil
}

// 在sql更新之前
// ----------------------------------------------------------------------------------------------------------
func (s *SecurityType) BeforeSave(tx *gorm.DB) (err error) {
	var count int64
	if err := tx.Model(&SecurityType{}).Where("name = ? ", s.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("密保问题不能重复，请检查更新")
	}
	return nil
}

// 增加单个密保问题
// ----------------------------------------------------------------------------------------------------------
func (s *SecurityType) CreateSecurity() error {
	return Gorm.Create(s).Error
}

// 查询所有成员
// ----------------------------------------------------------------------------------------------------------
func (s SecurityType) AllSecurity() ([]SecurityType, error) {
	var allItem = make([]SecurityType, 0)
	err := Gorm.Find(&allItem).Error
	return allItem, err
}

// 根据密保问题ID查询
// ----------------------------------------------------------------------------------------------------------
func (s *SecurityType) QuerySecurity(id uint) error {
	return Gorm.Where("id = ?", id).First(s).Error
}

// 修改此密保信息
// ----------------------------------------------------------------------------------------------------------
func (s *SecurityType) UpdateScurity(name string) error {
	return Gorm.Model(&SecurityType{}).Where("id = ?", s.ID).Update("name", name).Error
}

// 删除此密保信息
// ----------------------------------------------------------------------------------------------------------
func (s *SecurityType) DelScurity() error {
	return Gorm.Delete(s).Error
}
